<!--
 * @Descripttion: 商品详情
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors  : cxguo
 * @LastEditTime : 2019-12-26 16:58:11
 -->
<template>
  <div class="app-container paddingT50">
    <!-- 基本数据: {{ baseData }} <br><br>
    多单位数据: {{ unitData }} <br><br>
    选中的规格数据: {{ selectSpecsData }} <br><br>
    规格Table数据: {{ specsTableData }} <br><br>
    多价格数据: {{ priceData }} <br><br>
    多仓库数据: {{ stockData }} <br><br> -->
    <affix>
      <div class="paddingLR20 clearfix">
        <el-card shadow="never" class="oper-btn-card">
          <div class="clearfix">
            <el-button type="primary" size="medium" class="fl" :loading="btnLoading.save" @click="btnSave('add')">保存并新增</el-button>
            <!-- <el-button type="default" size="medium" class="fl" :loading="btnLoading.save" @click="btnSave('copyadd')">保存并复制新增</el-button> -->
            <el-button type="default" size="medium" class="fl" :loading="btnLoading.save" @click="btnSave">保 存</el-button>
            <el-button type="default" size="medium" class="fl" @click="btnCancle">取 消</el-button>
            <!-- <el-button type="primary" size="medium" class="fl" @click="btnGetPostData">获取post数据</el-button> -->
          </div>
        </el-card>
      </div>
    </affix>
    <el-card shadow="never" class="border-radius-none margin-t2">
      <el-tabs v-model="tabName" :tab-position="'top'">
        <el-tab-pane label="基础信息" name="base">
          <good-base ref="goodBase" :multi="multi" />
          <good-unit v-if="isMulUnit" ref="goodUnit" :multi="multi" class="margin-t40" />
          <good-specs
            v-if="isMulSpecs"
            ref="goodSpecs"
            :unit-data="unitData"
            :base-data="baseData"
            :multi="multi"
            class="margin-t40"
          />
          <barcode v-if="isShowBarcode" ref="barcode" class="margin-t40" :unit-data="unitData" :select-specs-data="selectSpecsData" />
        </el-tab-pane>
        <el-tab-pane v-if="isShowPrice" name="price" label="价格">
          <good-price ref="goodPrice" :unit-data="unitData" :select-specs-data="selectSpecsData" />
        </el-tab-pane>
        <el-tab-pane v-if="isShowStock" name="stock" label="库存">
          <good-stock ref="goodStock" :select-specs-data="selectSpecsData" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<script>
import { saveData } from '@/api/goods/goods'
import { oftenuse } from '@/libs/mixins'
import clonedeep from 'clonedeep'
import GoodBase from './base'
import GoodPrice from './price'
import GoodStock from './stock'
import GoodSpecs from './specs'
import GoodUnit from './unit'
import Barcode from './barcode'
import Affix from '@/components/Affix'

export default {
  name: 'GoodSaveMain',
  components: { GoodBase, GoodPrice, GoodStock, GoodSpecs, GoodUnit, Barcode, Affix },
  mixins: [oftenuse],
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      comps: {}, // 组件
      multi: {},
      hasEditCreated: false,
      dataObj: {},
      iframe: {},
      tabName: 'base'
    }
  },
  computed: {
    /**
     * 是否多单位
     */
    isMulUnit: function() {
      return this.multi.unit
    },
    /**
     * 是否多规格
     */
    isMulSpecs: function() {
      return this.multi.specs
    },
    isShowPrice: function() {
      const hasSpecs = !(this.selectSpecsData.length === 0)
      const hasUnit = !(this.unitData.length === 0)
      return hasSpecs && hasUnit
    },
    isShowStock: function() {
      return this.isShowPrice
    },
    isShowBarcode: function() {
      const hasSpecs = !(this.selectSpecsData.length === 0)
      const hasUnit = !(this.unitData.length === 0)
      if (this.isMulSpecs || this.isMulUnit) {
        if (hasSpecs && hasUnit) {
          return true
        }
      }
      return false
    },
    /**
     * 基础数据
     */
    baseData: function() {
      const goodBaseComp = this.comps.goodBase
      if (!goodBaseComp) return {}
      return clonedeep(goodBaseComp.dataObj)
    },
    /**
     * 单位post数据
     */
    unitData: function() {
      if (!this.isMulUnit) {
        const goodBase = this.comps.goodBase
        if (!goodBase) return []
        return goodBase.getUnit()
      } else {
        const goodUnitComp = this.comps.goodUnit
        if (!goodUnitComp) return []
        else return goodUnitComp.getGoodUnitData()
      }
    },
    /**
     * 价格post数据
     */
    priceData: function() {
      const goodPriceComp = this.comps.goodPrice
      if (!goodPriceComp) return []
      return goodPriceComp.pricePostData
    },
    /**
     * 仓库post数据
     */
    stockData: function() {
      const goodStockComp = this.comps.goodStock
      if (!goodStockComp) return []
      return goodStockComp.stockPostData
    },
    /**
     * 规格里，只包含规格数据
     */
    spTableData: function() {
      const goodSpecsComp = this.comps.goodSpecs
      if (!goodSpecsComp) return null
      return goodSpecsComp.spTableData
    },
    /**
     * 规格里，表所有的数据
     */
    specsTableData: function() {
      if (this.isMulSpecs) {
        const goodSpecsComp = this.comps.goodSpecs
        if (!goodSpecsComp) return []
        return goodSpecsComp.getSpTableData()
      } else {
        return []
      }
    },
    /**
     * 规格里选中的规格数据
     */
    selectSpecsData: function(params) {
      if (this.isMulSpecs) {
        const goodSpecsComp = this.comps.goodSpecs
        if (!goodSpecsComp) return []
        return goodSpecsComp.selectSpecsData
      } else {
        if (!this.baseData.specs) return []
        const obj = { 默认: [this.baseData.specs] }
        return [obj]
      }
    }
  },
  watch: {
    'isShowBarcode': {
      handler(val) {
        this.$set(this.multi, 'barcode', val)
      }
    }
  },
  created() {
  },
  destroyed() {
  },
  updated() {
    this.setComponents()
  },
  mounted() {
    this.setComponents()
  },
  methods: {
    btnGetPostData() {
      const goodsSpu = this.getSpuData()
      const goodsskuList = this.getSkuData()
      const goodsPriceList = this.getPriceData()
      const stockList = this.getStockData()
      console.log('商品SPU数据: ', goodsSpu)
      console.log('商品SKU数据: ', goodsskuList)
      console.log('商品Price数据: ', goodsPriceList)
      console.log('商品期初库存数据: ', stockList)
    },
    btnCancle() {
      this.resetData()
    },
    btnSave(oper) {
      this.valiData().then(res => {
        const goodsSpu = this.getSpuData()
        const goodsskuList = this.getSkuData()
        const goodsPriceList = this.getPriceData()
        const stockList = this.getStockData()
        const params = {
          goodsSpu, goodsskuList, goodsPriceList, stockList
        }
        this.setBtnLoading('save', true)
        this.saveGoodData(params).then((res) => {
          this.setBtnLoading('save', false)
          debugger
          if (!res.data.flag) return
          if (oper === 'add') {
            this.resetData()
          }
        })
      })
    },
    getSpuData() {
      const baseData = clonedeep(this.baseData)
      const supData = baseData
      const specsList = JSON.stringify(this.selectSpecsData)
      const unit = JSON.stringify(this.unitData)
      supData.specsList = specsList
      supData.unit = unit
      return supData
    },
    getBarCodePostData() {
      if (this.isShowBarcode) return this.$refs.barcode.getBarCodePostData()
      else {
        const unit = this.baseData.unit
        const barcode = this.baseData.barcode
        const obj = { unit, barcode }
        return [obj]
      }
    },
    getSkuData() {
      if (this.isMulSpecs) {
        return this.getMulSpecsSkuData()
      } else {
        const obj = this.baseData
        const barCodeData = this.getBarCodePostData()
        const { unitbase, unitvice } = this.getUnitSplitBase()
        const unitbaseId = unitbase.value
        obj.unitbase = JSON.stringify(unitbase)
        obj.unitvice = JSON.stringify(unitvice)
        obj.unitbaseId = unitbaseId
        obj.barcode = JSON.stringify(barCodeData[0])
        obj.name = `${obj.name}-${obj.specs}`
        return [obj]
      }
    },
    getUnitSplitBase() {
      const unitData = this.unitData
      const unitbaseDataArray = unitData.filter(item => { return item.default })
      const unitviceDataArray = unitData.filter(item => { return !item.default })
      const unitbaseDataObj = unitbaseDataArray.length ? unitbaseDataArray[0] : {}
      const unitbase = unitbaseDataObj
      const unitvice = unitviceDataArray
      return { unitbase, unitvice }
    },
    getMulSpecsSkuData() {
      const baseData = clonedeep(this.baseData)
      const specsTableData = clonedeep(this.specsTableData)
      const { unitbase, unitvice } = this.getUnitSplitBase()
      const unitbaseId = unitbase.value
      const result = []
      const barCodeData = this.getBarCodePostData()
      specsTableData.forEach((item, index) => {
        item.catId = baseData.catId
        item.catName = baseData.catName
        item.brandId = baseData.brandId
        item.unitbase = JSON.stringify(unitbase)
        item.unitvice = JSON.stringify(unitvice)
        item.unitbaseId = unitbaseId
        item.barcode = JSON.stringify(barCodeData[index])
        result.push(item)
      })
      return result
    },
    getPriceData() {
      return this.priceData
    },
    getStockData() {
      return this.stockData
    },
    saveGoodData(params) {
      return new Promise((resolve, reject) => {
        saveData(params).then(res => {
          resolve(res)
          const message = res.data.message
          if (!res.data.flag) return this.$notify.error({ title: '保存失败!', message: message })
          this.$notify.success({ title: message })
        }).catch(err => {
          reject(err)
        })
      })
    },
    valiData(callback) {
      const goodBaseComp = this.comps.goodBase
      const goodUnitComp = this.comps.goodUnit
      const goodSpecsComp = this.comps.goodSpecs
      const v1 = goodBaseComp.handleValid('goodBase')
      const v2 = new Promise((resolve, reject) => {
        if (!goodUnitComp) resolve()
        goodUnitComp.handleValid('goodUnit').then(_ => {
          resolve()
        }).catch(_ => {
          reject()
        })
      })
      const v3 = new Promise((resolve, reject) => {
        if (!goodSpecsComp) resolve()
        goodSpecsComp.valiData().then(_ => {
          resolve()
        }).catch(_ => {
          reject()
        })
      })
      return Promise.all([v1, v2, v3])
    },
    resetData() {
      const goodBaseComp = this.$refs.goodBase
      goodBaseComp.resetData()
      this.tabName = 'base'
    },
    setComponents: function() {
      this.$set(this.comps, 'goodBase', this.$refs.goodBase)
      this.$set(this.comps, 'goodUnit', this.$refs.goodUnit)
      this.$set(this.comps, 'goodSpecs', this.$refs.goodSpecs)
      this.$set(this.comps, 'goodPrice', this.$refs.goodPrice)
      this.$set(this.comps, 'goodStock', this.$refs.goodStock)
    }
  }
}
</script>

<style scoped>
</style>
